<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2019/12/19
 * Time: 12:15
 */

namespace app\push\controller;

use app\admin\model\WechatUserModel;
use app\common\model\ApplyLiveModel;
use GatewayWorker\Lib\Gateway;
use think\Db;
use app\common\model\CompanyModel;
use app\common\model\ChatRoomModel;
use app\common\model\ChatRoomLogModel;
use app\common\model\ChatMemberModel;
use app\common\model\ChatMemberLogModel;
use app\common\model\RedEnvelopesModel;

class EventsController
{
    /**
     * 每个进程启动
     * @param $worker
     */
    public static function onWorkerStart($worker)
    {
        //echo 'worker id ...'.$worker->id.PHP_EOL;

        if ($worker->id == 2) {
            echo 'this is workerid 2' . PHP_EOL;
        }
    }

    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
//        $where = [
//            'end_time'  => ['<', time()]
//        ];
//        Db::name('apply_live')->where($where)->setField('is_overdue', 1);


        global $num;

        // 向当前client_id发送数据

        // 向所有人发送
        //Gateway::sendToAll("$client_id login\r\n");
        echo "connect" . ++$num . ":" . $client_id . "\n";

        // sendToClient 向某个客户端连接发消息
        Gateway::sendToClient($client_id, json_encode([
            'type' => 'init',
            'client_id' => $client_id
        ]));
    }

    /**
     * 有消息时
     * @param int $client_id
     * @param mixed $message
     */
    public static function onMessage($client_id, $message)
    {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:" . json_encode($_SESSION) . " onMessage:" . $message . "\n";

        // 客户端传递的是json数据
        $message_data = json_decode($message, true);
        var_dump($message_data);

        if (!$message_data) {
            return;
        }

        var_dump($message_data);

        // 根据类型执行不同的业务
        switch ($message_data['type']) {
            // 客户端登录 message格式: {type:login, name:xx, room_id:1} ，添加到客户端，广播给所有客户端xx进入聊天室
            case 'login':
                // 判断是否有房间号
                echo '进login了';

                if (!isset($message_data['room_id'])) {
                    throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message");
                }
                // 把房间号昵称放到session中
                $room_id = $message_data['room_id'];
                echo $room_id . '看看\n';

                $client_name = htmlspecialchars($message_data['client_name']);
                $_SESSION['room_id'] = $room_id;
                $_SESSION['client_name'] = $client_name;

                if (isset($message_data['member_no'])) {
                    $_SESSION['member_no'] = $message_data['member_no'];
                }

                // 获取房间内所有用户列表
                $clients_list = Gateway::getClientSessionsByGroup($room_id);

                foreach ($clients_list as $tmp_client_id => $item) {
                    if (isset($item['member_no'])) {
                        $key = 'company';
                        $content = $item['member_no'];
                        if (strpos($content, $key) !== false) {
                            //包含
                            $clients_list[$tmp_client_id] = $item['client_name'] . '(公司)';
                        } else {
                            $clients_list[$tmp_client_id] = $item['client_name'] . $item['member_no'];
                        }
                    } else {
                        $clients_list[$tmp_client_id] = $item['client_name'];
                    }

                }
                if (isset($message_data['member_no'])) {
                    $key = 'company';
                    $content = $message_data['member_no'];
                    if (strpos($content, $key) !== false) {
                        //包含
                        $client_name = $client_name . '(公司)';
                    } else {
                        $client_name = $client_name . $message_data['member_no'];
                    }
                }
                $clients_list[$client_id] = $client_name;
                // 转播给当前房间的所有客户端，xx进入聊天室 message {type:login, client_id:xx, name:xx}
                $new_message = array(
                    'type' => $message_data['type'],
                    'client_id' => $client_id,
                    'client_name' => htmlspecialchars($client_name),
                    'time' => date('Y-m-d H:i:s'),
                    'room_id' => $room_id
                );

                Gateway::sendToAll(json_encode([
                    'type' => 'send_to_all',
                    'go_to' => 1,
                    'client_id' => $client_id,
                    'client_name' => htmlspecialchars($client_name),
                    'time' => date('Y-m-d H:i:s'),
                    'room_id' => $room_id,
                    'desc' => '房间号' . $room_id . '直播开始了'
                ]));

                Gateway::sendToGroup($room_id, json_encode($new_message));
                Gateway::joinGroup($client_id, $room_id);
                // 给当前用户发送用户列表
                $new_message['client_list'] = $clients_list;

                Gateway::sendToCurrentClient(json_encode($new_message));

                // 获取房间内所有用户列表
                $clientList = Gateway::getClientSessionsByGroup($room_id);

                if (isset($message_data['role']) && $message_data['role'] == 'company') {
                    echo 'asdfg' . "\n";

                    // 说明发送login的是公司
                    echo $room_id . "\n";


                    $company_id = explode('company', $message_data['member_no'])[1];

                    $res = company_chat_room($company_id, $room_id, 1, $client_id);

                    $apply = ApplyLiveModel::get(['id' => $room_id]);
                    $apply->is_open = 1;
                    $apply->save();

                    //var_dump($res);
                }
                if (isset($message_data['role']) && $message_data['role'] == 'user') {
                    // 说明发送login的是用户
                    $wechat = WechatUserModel::get(['member_no' => $message_data['member_no']]);
                    $res = user_chat_room($wechat['id'], $room_id, 1, $client_id);
                }
                $getClientCount = Gateway::getClientCountByGroup($room_id);
                $xuni_number = 0;
                $apply_live = ApplyLiveModel::get($room_id);
                if ($apply_live) {
                    $xuni_number = $apply_live['online_number'];
                }
                $getClientCount = $getClientCount + $xuni_number;

                Gateway::sendToGroup($room_id, json_encode([
                    'type' => 'getClientCount',
                    'num' => $getClientCount,
                    'sqlList' => Db::name('chat_member')->where('live_id', $room_id)->where('is_online', 1)->select()->all(),
                    'merchant_is_back' => 0,
                ]));
                return;

            case 'no_say':
                echo "我接收到no_say";
                $room_id = $message_data['room_id'];
                $to_member_no = $message_data['to_member_no'];

                no_say($room_id, $to_member_no);

                Gateway::sendToAll(json_encode([
                    'type' => 'no_say',
                    'client_id' => $client_id,
                    'time' => date('Y-m-d H:i:s'),
                    'room_id' => $room_id,
                    'member' => Db::name('chat_member')->where('live_id', $room_id)->where('is_online', 1)->select()->all(),
                    'no_say_member' => Db::name('chat_member')->where('live_id', $room_id)->where('is_banned', 1)->select()->all(),
                ]));

                return;

            case 'jiechu_no_say':
                echo "我接收到jiechu_no_say";

                $room_id = $message_data['room_id'];
                $to_member_no = $message_data['to_member_no'];
                jiechu_no_say($room_id, $to_member_no);

                Gateway::sendToAll(json_encode([
                    'type' => 'jiechu_no_say',
                    'client_id' => $client_id,
                    'time' => date('Y-m-d H:i:s'),
                    'room_id' => $room_id,
                    'member' => Db::name('chat_member')->where('live_id', $room_id)->where('is_online', 1)->select()->all(),
                    'jiechu_say_member' => Db::name('chat_member')->where('live_id', $room_id)->where('is_banned', 0)->select()->all(),
                ]));


                return;

            case 'lottery_start':
                echo "我接收到lottery_start";

                live_lottery($message_data['live_id'], $message_data['company_id'], $message_data['member_no']);

                Gateway::sendToGroup($message_data['live_id'], json_encode([
                    'type' => 'lottery_start',
                    'member_no' => $message_data['member_no'],
                ]));

                return;

            case 'send_red_envelopes':
                $room_id = $message_data['live_id'];
                $company_id = $message_data['company_id'];
                $total = $message_data['total'];
                $num = $message_data['num'];
                $info = CompanyModel::get($company_id);

                $red_envelopes_id = send_red_envelopes($room_id, $company_id, $total, $num);

                Gateway::sendToGroup($room_id, json_encode([
                    'type' => 'send_red_envelopes',
                    'red_envelopes_id' => $red_envelopes_id
                ]));

                return;

            case 'grab':
                echo "我接收到grab";

                $red_envelopes = RedEnvelopesModel::get($message_data['red_envelopes_id']);
                //var_dump($red_envelopes);
                if ($red_envelopes['is_end'] == 1) {
                    // 红包已抢完
                    Gateway::sendToCurrentClient(json_encode([
                        'type' => 'red_envelopes_end',
                        'red_envelopes_id' => $message_data['red_envelopes_id']
                    ]));
                } else {
                    // 开始 抢红包
                    //var_dump($red_envelopes->toArray());

                    $get_total = grab($message_data['red_envelopes_id'], $message_data['live_id'], $red_envelopes['company_id'], $message_data['user_type'], $message_data['member_id']);


                    Gateway::sendToCurrentClient(json_encode([
                        'type' => 'grab',
                        'red_envelopes_id' => $message_data['red_envelopes_id'],
                        'get_total' => $get_total
                    ]));
                }

                return;

            case 'send_coupons':
                // 告诉房间的其他人  领优惠券指令
                Gateway::sendToGroup($message_data['live_id'], json_encode([
                    'type' => 'send_coupons',
                    'coupon_id' => $message_data['coupon_id'],
                ]));

                return;

            // 客户端回应服务端的心跳

            // 客户端定时每X秒(推荐小于60秒)向服务端发送特定数据，服务端设定为X秒没有收到客户端心跳则认为客户端掉线，并关闭连接触发onClose回调。
            case 'pong':


                return;


            // 客户端发言 message: {type:say, to_client_id:xx, content:xx}
            case 'say':
                // 非法请求
                if (!isset($_SESSION['room_id'])) {
                    throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}");
                }
                $room_id = $_SESSION['room_id'];
                $client_name = $_SESSION['client_name'];

                // 私聊
                if ($message_data['to_client_id'] != 'all') {
                    $new_message = array(
                        'type' => 'say',
                        'from_client_id' => $client_id,
                        'from_client_name' => $client_name,
                        'to_client_id' => $message_data['to_client_id'],
                        'content' => "<b>对你说: </b>" . nl2br(htmlspecialchars($message_data['content'])),
                        'time' => date('Y-m-d H:i:s'),
                    );
                    Gateway::sendToClient($message_data['to_client_id'], json_encode($new_message));
                    $new_message['content'] = "<b>你对" . htmlspecialchars($message_data['to_client_name']) . "说: </b>" . nl2br(htmlspecialchars($message_data['content']));
                    return Gateway::sendToCurrentClient(json_encode($new_message));
                }

                $new_message = array(
                    'type' => 'say',
                    'from_client_id' => $client_id,
                    'from_client_name' => $client_name . $message_data['member_no'],
                    'to_client_id' => 'all',
                    'content' => nl2br(htmlspecialchars($message_data['content'])),
                    'time' => date('Y-m-d H:i:s'),
                );
                return Gateway::sendToGroup($room_id, json_encode($new_message));

            case 'heartbeat':
                $client_name = htmlspecialchars($message_data['client_name']);

                $list = [];

                if (isset($message_data['room_ids'])) {
                    $room_ids = $message_data['room_ids'];
                    $list = ApplyLiveModel::where('id', 'in', $room_ids)->select();
                    if ($list) {
                        foreach ($list as $k => $v) {
                            if (time() >= $v['start_time']) {
                                // 可以开始直播
                                $list[$k]['is_start'] = 1;
                            } else {
                                // 直播 未开始
                                $list[$k]['is_start'] = 0;
                            }
                        }
                    }
                }

                $new_message = array(
                    'type' => $message_data['type'],
                    'client_id' => $client_id,
                    'client_name' => htmlspecialchars($client_name),
                    'time' => date('Y-m-d H:i:s'),
                    'list' => $list
                );


                Gateway::sendToCurrentClient(json_encode($new_message));
                return;

        }
    }

    /**
     * 当客户端断开连接时
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id)
    {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";

        // 从房间的客户端列表中删除
        if (isset($_SESSION['room_id'])) {
            $room_id = $_SESSION['room_id'];
            $apply_live = ApplyLiveModel::get($room_id);
            $new_message = array(
                'type' => 'logout',
                'from_client_id' => $client_id,
                'from_client_name' => $_SESSION['client_name'] . $_SESSION['member_no'],
                'time' => date('Y-m-d H:i:s')
            );
            Gateway::sendToGroup($room_id, json_encode($new_message));

            // 获取房间内所有用户列表
            $clientList = Gateway::getClientSessionsByGroup($room_id);

//            var_dump($clientList);
//            var_dump(count($clientList));

            Gateway::sendToAll(json_encode([
                'type' => 'send_to_all',
                'go_to' => 2,
                'from_client_id' => $client_id,
                'from_client_name' => $_SESSION['client_name'],
                'time' => date('Y-m-d H:i:s'),
                'room_id' => $room_id,
                'desc' => '直播房间号' . $room_id . '的' . $_SESSION['client_name'] . '离开了'
            ]));


            $key = 'company';
            $content = $_SESSION['member_no'];
            if ($content) {
                if (strpos($content, $key) !== false) {
                    //包含
                    //公司
                    $companyId = explode('company', $content);
                    $res = company_chat_room($companyId[1], $room_id, 0, $client_id);

                    if ($apply_live['is_open'] != 3) {
                        $apply_live->is_open = 3;
                        $apply_live->save();
                    }
                } else {
                    //用户
                    $wechat_user = WechatUserModel::get(['member_no' => $_SESSION['member_no']]);
                    $res = user_chat_room($wechat_user['id'], $room_id, 0, $client_id);
                }
            }
            $getClientCount = Gateway::getClientCountByGroup($room_id);

            $xuni_number = 0;

            if ($apply_live) {
                $xuni_number = $apply_live['online_number'];
            }

            $getClientCount = $getClientCount + $xuni_number;

            $apply_live_info = ApplyLiveModel::get($room_id)->toArray();

            $online_back = Db::name('chat_member')
                ->where('live_id', $room_id)
                ->where('is_online', 0)
                ->where('type', 2)
                ->where('member_id', $apply_live_info['company_id'])
                ->find();

            if ($online_back) {
                $merchant_is_back = 1;// 已离开
            } else {
                $merchant_is_back = 0;// 未离开
            }

            Gateway::sendToGroup($room_id, json_encode([
                'type' => 'getClientCount',
                'num' => $getClientCount,
                'sqlList' => Db::name('chat_member')->where('live_id', $room_id)->where('is_online', 1)->select()->all(),
                'merchant_is_back' => $merchant_is_back
            ]));
        }
        // 向所有人发送
        // echo "the heart beats stoped.\n";
        // echo "the user logouted.\n";


    }


}